using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using SpoonCore2.Client;

namespace SpoonCore2.Service.KeyExchange
{
	public class SpoonCert
	{
		private const int KeySizes = 2048;
		private readonly SpoonIdentifier _id;
		private readonly SortedList<string, string> _data = new SortedList<string, string>();
		private readonly RSACryptoServiceProvider _rsa;

		public SpoonCert(BinaryReader br)
		{
			_id = new SpoonIdentifier(br);
			byte[] data = br.ReadBytes(br.ReadInt32());
			_rsa.ImportCspBlob(data);

			int count = br.ReadInt32();
			while (count > 0)
			{
				string key = br.ReadString();
				string value = br.ReadString();
				_data.Add(key, value);

				count--;
			}
		}

		public SpoonCert(SpoonIdentifier id)
		{
			_id = id;
			_rsa = new RSACryptoServiceProvider(KeySizes);
		}

		public SpoonIdentifier Id
		{
			get { return _id; }
		}

		public byte[] Decrypt(byte[] data)
		{
			return _rsa.Decrypt(data, false);
		}

		public byte[] Encrypt(byte[] data)
		{
			return _rsa.Encrypt(data, false);
		}

		public byte[] GetBytes()
		{
			return GetBytes(false);
		}

		public byte[] GetBytes(bool includePrivate)
		{
			MemoryStream stream = new MemoryStream();
			BinaryWriter bw = new BinaryWriter(stream);

			bw.Write(_id.GetBytes());
			bw.Write(_rsa.ExportCspBlob(includePrivate));
			
			return stream.ToArray();
		}

		/*public static void Main()
		{
			SpoonCert cert = new SpoonCert(new SpoonIdentifier());
			
			byte[] test = new byte[240];
			Random rand = new Random();
			rand.NextBytes(test);

			byte[] testNew = cert.Encrypt(test);
			byte[] test2 = cert.Decrypt(testNew);
		}*/
	}
}